﻿using System.Threading.Tasks;
using Devonline.Core;
using Devonline.Entity;
using Devonline.Identity.Admin.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Devonline.Identity.Admin.Controllers
{
    /// <summary>
    /// 基础数据管理
    /// </summary>    
    [Route("api/[controller]")]
    [SecurityHeaders]
    [ApiController]
    [Authorize(Roles = AppSettings.GROUP_MAINTAINERS)]
    public class ParametersController : ControllerBase
    {
        private readonly IdentityDbContext _context;
        private readonly ILogger<ParametersController> _logger;

        public ParametersController(
            IdentityDbContext context,
            ILogger<ParametersController> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [EnableQuery]
        public IActionResult Get()
        {
            _logger.LogInformation("user {user} query the parameter list", User.Identity.Name);
            return Ok(_context.Parameters);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateAsync(ParameterViewModel viewModel)
        {
            _logger.LogInformation("user {user} will add the parameter {parameter}", User.Identity.Name, viewModel.Key);
            if (await _context.Parameters.AnyAsync(x => x.Index == viewModel.Index))
            {
                return BadRequest($"基础数据编号: {viewModel.Index} 已经存在!");
            }

            var parameter = new Parameter
            {
                Index = viewModel.Index,
                Key = viewModel.Key,
                Value = viewModel.Value,
                Text = viewModel.Text,
                ParentId = viewModel.ParentId
            };

            parameter.Create(User.Identity.Name);
            _context.Parameters.Add(parameter);

            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to add the parameter {parameter}", User.Identity.Name, parameter.Key);
                return Ok();
            }

            return BadRequest($"创建基础数据 {viewModel.Key} 没有成功!");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> ChangeAsync(string id, ParameterViewModel viewModel)
        {
            _logger.LogInformation("user {user} will change the parameter {parameter}", User.Identity.Name, id);
            var parameter = await _context.Parameters.FindAsync(id);
            if (parameter == null)
            {
                return NotFound();
            }

            viewModel.CopyTo(parameter);
            _context.Parameters.Update(parameter);

            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to change the parameter {parameter}", User.Identity.Name, parameter.Key);
                return Ok();
            }

            return BadRequest($"修改基础数据 {viewModel.Key} 没有成功!");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAsync(string id)
        {
            _logger.LogInformation("user {user} will delete the parameter {parameter}", User.Identity.Name, id);
            var parameter = await _context.Parameters.FindAsync(id);
            if (parameter == null)
            {
                return NotFound();
            }

            _context.Parameters.Remove(parameter);
            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to delete the parameter {parameter}", User.Identity.Name, parameter.Key);
                return Ok();
            }

            return BadRequest($"删除基础数据 {parameter.Key} 出错!");
        }
    }
}
